#! /usr/bin/env python
# -*- coding:utf-8 -*-

import time

def fetch(url):
    try:
        from google.appengine.api.urlfetch import fetch
        return fetch(url).content
    except:
        import urllib2
        return urllib2.urlopen(url).read()

def md5_hash(text):
    try:
        from gluon.utils import md5_hash
        return md5_hash(text)
    except ImportError:
        import md5
        md5.update(text)
        return md5.hexdigest().upper()
    
class Time(object):
    def __init__(self):
        self.ISOTIMEFORMAT = '%Y-%m-%d %X'
    def ISOString2Time(self, s):
        '''
        convert a ISO format time to second
        from:2006-04-12 16:46:40 to:23123123
        把一个时间转化为秒
        '''
        return time.strptime(s, self.ISOTIMEFORMAT)
    def Time2ISOString(self, s):
        '''
        convert second to a ISO format time
        from: 23123123 to: 2006-04-12 16:46:40
        把给定的秒转化为定义的格式
        '''
        return time.strftime(self.ISOTIMEFORMAT, time.localtime( float( s ) ) )
    def dateMinDate(self, d1, d2 ):
        '''
        minus to iso format date,return seconds
        计算2个时间相差多少秒
        '''
        d1=self.ISOString2Time( d1 )
        d2=self.ISOString2Time( d2 )
        return time.mktime( d1 )-time.mktime( d2 )
    def dateplustime(self, d, t ):
        '''
        d=2006-04-12 16:46:40
        t=2小时
        return  2006-04-12 18:46:40
        计算一个日期相差多少秒的日期,time2sec是另外一个函数，可以处理，3天，13分钟，10小时等字符串，回头再来写这个，需要结合正则表达式。
        '''
        return self.Time2ISOString( time.mktime( self.ISOString2Time( d ) )+time2sec( t ) )
    
if __name__ == '__main__':
    tm = Time()
    print time.localtime()
    print time.strftime(tm.ISOTIMEFORMAT)
    print tm.Time2ISOString('23123123')
    print tm.ISOString2Time('2006-04-12 16:46:40')
    print tm.dateMinDate( '2006-04-12 22:46:40', '2006-04-12 10:46:40')
#    print tm.dateplustime('2006-04-12 16:46:40', '2小时')
